package cron

import (
	"duanju-mq/db"
	"duanju-mq/handle"
	"duanju-mq/lib/firebase"
	"duanju-mq/pkg/app"
	"duanju-mq/pkg/formatStruct"
	"duanju-mq/pkg/log"
	"fmt"
	"strings"
	"time"
)

var (
	//前最大天数
	maxDay     int64 = 3
	daySeconds int64 = 3600 * 24
)

type bonusHistory struct {
	Id           int64  `json:"id" field:"id"`
	ActivityName string `json:"activity_name" field:"activity_name"`
	UserDeviceId string `json:"user_device_id" field:"user_device_id"`
	Expired      int64  `json:"expired" field:"expired"`           //过期时间
	Bonus        int64  `json:"bonus" field:"bonus"`               //赠送
	RemainBonus  int64  `json:"remain_bonus" field:"remain_bonus"` //剩余
	CreateAt     int64  `field:"create_at" json:"create_at"`
	UpdatedAt    int64  `field:"updated_at" json:"updated_at"`
	Deleted      int64  `field:"deleted" json:"deleted"` //  标识记录是否被删除（0：没有被删除，1：被删除）
}

type bonusNotify struct {
	Id           int64  `json:"id" field:"id"`
	UserDeviceId string `json:"user_device_id" field:"user_device_id"`
	RemainBonus  int64  `json:"remain_bonus" field:"remain_bonus"` //剩余
}

func init() {
	db.AfterDbOpen(func() {
		app.Async(func() {
			checkUpcomingExpired()
		})
	})
}

func checkUpcomingExpired() {
	<-time.After(time.Second * 10)
	for {
		log.Info("执行定时检查赠送即将过期，推送")
		checkBonusExpired()
		time.Sleep(time.Minute)
	}
}

func checkBonusExpired() {

	var (
		now       = time.Now().Unix()
		queryCond = []string{
			"remain_bonus > 0",
			"expired > ?",
			"expired < ?",
		}

		pageIndex = 1
		pageSize  = 30
	)

	for {
		//获取一批即将的过期bonus
		querySql := fmt.Sprintf("where %v group by user_device_id limit ? offset ?", strings.Join(queryCond, " and "))

		historyFromDb, err := getBonusHistoryFromDb(querySql, now, now+maxDay*daySeconds, pageSize, (pageIndex-1)*pageSize)
		if err != nil {
			return
		}

		if len(historyFromDb) < 1 {
			return
		}

		for _, v := range historyFromDb {
			bonusL := firebase.ShiftLeft(fmt.Sprintf("%d", v.RemainBonus), 4, 0)
			msg := &firebase.Message{
				Notification: &firebase.Notification{
					Title: "Bonus is about to expire, exciting content waiting for you to watch.",
					Body:  fmt.Sprintf("Your %s bonus will expire.\nClick on Me to receive more benefits", bonusL),
				},
				Condition: fmt.Sprintf("'%s' in topics", v.UserDeviceId),
			}
			handle.HandleMsgPush(v.UserDeviceId, msg)
		}

		pageIndex++

	}
}

func getBonusHistoryFromDb(sqlCond string, values ...interface{}) ([]*bonusNotify, error) {

	querySql := "select `id`,`user_device_id`,sum(`remain_bonus`) remain_bonus " +
		fmt.Sprintf(" from `bonus_history` %v", sqlCond)

	rows, err := db.MqDB().Query(querySql, values...)
	if err != nil {
		log.Err(fmt.Sprintf("getBonusHistoryFromDb %v %+v %+v", querySql, values, err))
		return nil, err
	}
	defer rows.Close()

	var list []*bonusNotify
	for rows.Next() {
		item := &bonusNotify{}
		if err = rows.Scan(formatStruct.ParseStructFields(item).GetPtrs()...); err != nil {
			log.Err(fmt.Sprintf("getBonusHistoryFromDb %v %+v %+v", querySql, values, err))
			return nil, err
		}
		list = append(list, item)
	}

	return list, err
}
